if(!window["vg"]) {
	vg = {};
}

if(!vg.utility) {
	vg.utility = {};
}

vg.utility.Uploader = (function () {
	var input;
	
	var xPaths = {
	    formid : "/Application/data/inputxml/formvariables/formid",
		fileName : "./soap:Envelope/soap:Body/ns1:UploadFile/ns1:fileName",
		componentPath : "./soap:Envelope/soap:Body/ns1:UploadFile/ns1:componentPath",
		filePath : "./soap:Body/ns1:UploadFileResponse/ns1:tuple/ns1:old/ns1:upload/ns1:upload/ns1:DeleteTempFile/ns1:FilePath"
	}
    var namespaces = {
        'ns1': "http://schemas.cordys.com/bsf/uc/webapps/1.0/ucappsutil",
        'soap': "http://schemas.xmlsoap.org/soap/envelope/"
    }

	/**
	 * To set the uploader for a particular button
	 * @param {Object} inputObj
	 * parentDivId - There should be a containing div inside which the "Browse.." button for uploading will be 
	 * placed
	 * imageId - There should be a static hidden image in the form. The field id of that image has to be given here
	 * responseHandler - The handler to be called after uploading.
	 */
	var setUploader = function(inputObj) {
		inputObj.formElmtId = this.formElmtPrefix + (this.formElmtCount++);
		inputObj.buttonId = this.uploadBtnPrefix + (this.uploadBtnCount++);
		var uploadButtonContainer = document.getElementById(inputObj.parentDivId);
		uploadButtonContainer.innerHTML = "<form xmlns='' action='com.eibus.web.tools.upload.Upload.wcp' id='" + inputObj.formElmtId + "' name='uploadpicture' style='float:right' enctype='multipart/form-data' method='post'><label id='loc_uploadLabel' class='cabinet'><input id='" + inputObj.buttonId + "' type='file' size='1' width='0px' name='file1' class='file'/></label></form>";
		inputObj.uploadButton = document.getElementById(inputObj.buttonId);
		inputObj.formElement = document.getElementById(inputObj.formElmtId);
		inputObj.uploadButton.onchange = bindFunction(browseClick, inputObj);
	    inputObj.uploadButton.organization = application.organization;
	    inputObj.uploadButton.timeout = 300000000;
	    inputObj.uploadButton.onupload = bindFunction(uploadResponseHandler, inputObj);		
		input = inputObj;
	}
	
	/**
	 * browseClick function is bound to the inputObj as its this object. So reference to this inside browseClick refers
	 * to the inputObj set in setUploader
	 */
	var browseClick = function () {
	    var fileExtension = "";
	    try {
	        var filePath = this.uploadButton.value;  
	        if(filePath != "") {
				upload.call(this, filePath, fileName)
	        } else {
	           application.notify("Please select a file");
	        }
	    } catch(error) {        
	        return null;
	    }	
	}
	
	/**
	 * upload is called from browseClick with the inputObj as its this
	 * @param {Object} filePath
	 */
	var upload = function (filePath)
	{
	    var orgDN = application.organization;
	    var orgName = orgDN.substring(2,orgDN.indexOf(","));	
		!this.fileName && (this.fileName = filePath.substring(filePath.lastIndexOf("\\")+1).toLowerCase());
		this.beforeUploadHandler && this.beforeUploadHandler(this.fileName);
		var componentPath = orgName + "/Picture Images/" + getFormId() + "/" + this.imageId;
		var uploadFileNodeRequest = cordys.loadXMLDocument('<SOAP:Envelope xmlns:SOAP="http://schemas.xmlsoap.org/soap/envelope/"><SOAP:Body><UploadFile xmlns="http://schemas.cordys.com/bsf/uc/webapps/1.0/ucappsutil"><type>field_image</type><fileName /><filePath>Upload:FilePath1</filePath><componentPath /></UploadFile></SOAP:Body></SOAP:Envelope>');
	    cordys.setTextContent(cordys.selectXMLNode(uploadFileNodeRequest, xPaths.fileName, namespaces),this.fileName)
	    cordys.setTextContent(cordys.selectXMLNode(uploadFileNodeRequest, xPaths.componentPath, namespaces),componentPath)
	    application.addType(this.uploadButton, "wcp.library.util.Upload");
	    this.uploadButton.request = uploadFileNodeRequest;
		this.uploadButton.uploadFile(this.formElement);
	}	
	
	var uploadResponseHandler = function (eventObject) {
		var eventObj = this;
		if(window.application.event.status){
			eventObj.url = location.origin + cordys.getNodeText(eventObject.response, xPaths.filePath, "",  namespaces);
		} else {
			eventObj = false;
	 	}
		this.responseHandler && this.responseHandler(eventObj);
	}
	
	var getFormId = function () {
		var url = application.container.url;
		var result = url.match(/\/cordys\/(.*?)\.caf/);
		return result[1];
	}
	
	var bindFunction = function (functionObj, thisObj) {
		return function () {
			functionObj.apply(thisObj, arguments);
		}
	}
	
	var setFileName = function (fileName) {
		input.fileName = fileName;
	}
	
	return {
		setUploader : setUploader,
		setFileName : setFileName,
		formElmtPrefix : "browseButton",
		uploadBtnPrefix : "uploader",
		formElmtCount : 0,
		uploadBtnCount : 0
	}
})();
scriptCallback && scriptCallback("Uploader");